<template>
	<div v-waterMarker class="merak-float" v-loading="loading">
		<div class="header">
			<div class="leftTitle">
				<!-- <div class="icon" @click="emit('close',state.refresh,props.typeId)">
					<el-icon size="20">
						<ArrowLeft />
					</el-icon>
				</div> -->
				<div class="title">申请商品</div>
			</div>
			<div class="btnBoxs">
				<div class="icon" @click="emit('close',reloading_father,'1223123')">
					<el-icon size="20">
						<Close />
					</el-icon>
				</div>
			</div>
		</div>
		<div class="content merak-collapse-item">
			<div class="merak-float-overflow-y">
				 <div class="merak-table-wrapper" style="height:100%">
        <MerakXTable
		ref="tableDetailRef"
			v-bind="tableState"
			:columns-by-store="JSON.parse(JSON.stringify(state.columns))"
			:query-columns="handleQueryColumns"
			:query-data="handleQueryData"
			:params="state.params"
			:column-min-width="120"
		
					:handles="tableState.handles"
			:data="state.data"
			:batch-click="handleBatchClick"
			:batches="[{text: '批量修改厂家名称', color: 'green', type:'batch_factory_name'}]"
		  
			:await-params="true"
			:handler-click="handleHandlerClick"
      	:enabled-editor-by-auth="tableEditorAuth"
			@editor-click="handleEditorClick"
        >
          <template #custom_handle="{ row }">
			<el-button
             v-auth="{ authArr: authArr, key: 'productDel' }"
              type="danger"
              link
              @click="delFun(row?.apply_log_id)"
            >
              {{ $t("merak.delete") }}
            </el-button>
 
          </template>

          <!-- <template #express_pdf="{ row }">

          
            <span v-if="row.express_pdf==0">EAC版</span>
            <span v-if="row.express_pdf==1">EAC+简</span>
            <span v-if="row.express_pdf==2">简版</span>
           
             </template>
             -->



             
        </MerakXTable>
      </div>
			</div>
		</div>

		<div>

<el-dialog destroy-on-close v-model="edit_model" :width="500" align-center append-to-body>
  <template #header>
	<div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`marking_pending_application.${edit_modal_arr.curField}`) }}」</div>
  </template>
  <el-form ref="formRef" label-position="top" :model="edit_modal_arr">
	<el-select v-if="edit_modal_arr.curField=='factory_name'" class="qf_select" v-model="edit_modal_arr.curval"  filterable>
			<el-option :label="item.label" :value="item.value" v-for="item in dataFactory" :key="item" />		
		</el-select>
		<el-input v-else v-model="edit_modal_arr.curval" class="qf_input" />
  </el-form>
  <template #footer>
	<el-button @click="edit_model = false">{{ $t("merak.cancel") }}</el-button>
	<el-button  :loading="edit_loading" type="primary" @click="tdSave(edit_modal_arr)">{{
	  $t("merak.confirm")
	}}</el-button>
  </template>
</el-dialog>





<el-dialog destroy-on-close v-model="factory_model" :width="500" align-center append-to-body>
  <template #header>
	<div class="editor-title">批量修改厂家名称</div>
  </template>
  <el-form ref="factoryAllRef" label-position="top" :model="factoryAllForm">
	<el-select class="qf_select" v-model="factoryAllForm.factory"  filterable>
		<el-option :label="item.label" :value="item.value" v-for="item in dataFactory" :key="item" />		
	</el-select>
  </el-form>
  <template #footer>
	<el-button @click="factory_model = false">{{ $t("merak.cancel") }}</el-button>
	<el-button  :loading="factoryAll_loading" type="primary" @click="factoryAllSave()">{{
	  $t("merak.confirm")
	}}</el-button>
  </template>
</el-dialog>










</div>










	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import {
	getdetailDataApi,
	getdetailfieldApi,
	updatafieldApi,
	getFactory ,
	productSetTd,
	productdelete


  } from "@/api/modules/markingManagement/applicationFrom";
  import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
  import I18n from "@/languages/index";
  import { watch } from "vue";
  import MerakXTable, {
  MerakXTableInstance,
  MerakXTableColumn,
  MerakXTableProps,
  MerakXTableQuery
} from "@/components/MerakXTable";

const $t = I18n.global.t;


 const tableDetailRef = ref<MerakXTableInstance>();
  const state = reactive<{
  params: Record<string, any>;
  columns: MerakXTableColumn[];
}>({
  params: {
    key_words: ""
  },
  columns: []
});

	const props = defineProps<{
		rowData:any;
	}>();
	const loading = ref(false);
	const emit = defineEmits<{
		close : [refresh: boolean,typeId:string|number];
	}>();

const reloading_father=ref(false);
//批量操作
const handleBatchClick: MerakXTableInstance["batchClick"] = async ({ type, mode, selectedKeys }) => {
		console.log(selectedKeys)
		switch (type) {
			case "batch_factory_name":
			factory_model.value=true;
			selectArr.value=selectedKeys;
			factoryAllForm.factory='';
			factoryAll_loading.value=false;


				

			default:
			return;
		}
		};

//权限数据
let authArr = ref({});

//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    // if (curcheck_id.value[0].indexOf('-') > -1) {
    // 	var newarr = curcheck_id.value[0].split('-');
    // 	cur_type.value = newarr[1]

    // } else {
    // 	cur_type.value = curcheck_id.value[0];
    // }

    Object.assign(params, { ...page, keyword: params.search });
  }
   console.log(props.rowData)
   params["type_id"] = props.rowData.type_id;
   params["supplier_id"] = props.rowData.supplier_id;
   params["brand_id"] = props.rowData.brand_id;
   params["release_method_type"] = props.rowData.release_method_type;
   params["deliver_date"] = props.rowData.deliver_date;
   params["apply_order_type"] = props.rowData.apply_order_type;
   params["comments"] = props.rowData.comments;
   params["status"] = props.rowData.status;

   







//   for (let key of Object.keys(from)) {
//     if (!!from[key]) {
//       params[key] = from[key];
//     }
//   }
  return await getdetailDataApi(params).then(res => {
    // console.log(res)
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;
      Object.assign(authArr, data.auth_list);

      // 权限02
      authArr.value = res.auth_list;
  

      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
      return table_data;
    }
  });
};
//表头信息
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  return await getdetailfieldApi().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data as MerakXTableQuery.Columns;
      // 克隆表头数据作为列设置的对照数据
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));

      // return {
      // 	...data,
      // 	columns: [...data.columns].map(column => {
      // 	switch (column.field) {
      // 		case "merge_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		case "merge_prop_cn":
      // 		case "merge_prop_ru":

      // 		case "product_type":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop_id":
      // 		return { ...column, params: { editor: false } };
      // 		case "cc_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		default:
      // 		return { ...column };
      // 	}
      // 	})
      // };

      data.columns.map(column_ever => {
        console.log(column_ever);
        if (column_ever.field == "factory_name" || column_ever.field == "quantity"  || column_ever.field == "num_in_container" ) {
          column_ever["params"] = { editor: true };
        } else {
          column_ever["params"] = { editor: false };
        }
 
        // if(column_ever.field=="express_pdf"){

					
        //   column_ever["slots"]={ default: `express_pdf` }
        // }

        

      });

      console.log(data.columns);
      state.columns = data.columns;
      return data;
    }
  });
};
const handleNodeClick = (data: Tree) => {
  console.log(data);
};

const edit_model = ref(false);
const editForm = ref({
  aaa: "",
  bbb: ""
});


//删除

const delFun = (id) => {

confirmWarningMsg({
  msg: '确定要删除吗' ?? "",
  callback: (status: string) => {
	if (status === "confirm") {
		productdelete({apply_log_id:id}).then(({ code, message }) => {
		if (code == ResultEnum.SUCCESS) {
			tableDetailRef.value?.reloadData();
		  successMsg($t("merak.delete_success"));
		  reloading_father.value=true;
		} else {
		  failMsg(message);
		}
	  });
	}
  }
});
}

// 获取工厂
const dataFactory=ref();

const getFactoryFun = () => {

	getFactory({apply_log_id:props.rowData.apply_log_id}).then(({ code, message,data }) => { 
              if (code == ResultEnum.SUCCESS) {
				dataFactory.value=data.list; 
              
              } else {
                failMsg(message);
              }
            });

}




// 批量修改厂家名称
const factory_model=ref(false);
const factoryAllForm=ref({factory:''})
const factoryAllRef=ref();
const factoryAll_loading=ref(false)
const selectArr=ref([]);
// 批量修改厂家名称提交
const factoryAllSave = params => {
	console.log(selectArr.value)
	const selectArrstr = selectArr.value + ""
	factoryAll_loading.value=true;
	productSetTd({ apply_log_id: selectArrstr, field:'factory_id', value: factoryAllForm.value.factory }).then(res => {
	factoryAll_loading.value=false;
    if (res.code == ResultEnum.SUCCESS) {
		factory_model.value = false;
      tableDetailRef.value?.reloadData();
	  successMsg('操作成功');
    } else {
      failMsg(res.message);
    }
  });





	

}






//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  // console.log(params)

  let postParams = { ...params.params, keyword: params.search };
  state.params = postParams;
};


// 编辑表格
// 给予表格编辑权限
onMounted(async () => {
	state.params={}
	console.log("Sdfasdfsdaf")
	getFactoryFun();
});


const tableEditorAuth = computed(() => {
  let flag = false;

if (!!authArr.value?.productEdit?.show) {
  flag = true;
}
console.log(flag)
return flag;
});

const edit_modal_arr = ref({ curField: "", curval: "", rowKey: "" });

// 表格编辑事件
const handleEditorClick: MerakXTableInstance["onEditor-click"] = params => {
  console.log(params);
  edit_model.value = true;
  edit_modal_arr.value.curField = params.field;
  edit_modal_arr.value.rowKey = params.rowKey;
  edit_modal_arr.value.curval = params.value;
};



// 表格相关属性
// columnType: ['selection',{ type: "handle", width: 130, showHandleDropDown: true, slot: "custom_handle" }],

const tableState = reactive<MerakXTableProps>({
	columnsByStore: [],
	rowKey: "apply_log_id",
	columnType: [ 'selection',{type: "handle", width: 130, showHandleDropDown: true, slot: "custom_handle" }],
  });

// 操作列下拉选项点击事件
const handleHandlerClick: MerakXTableProps["handlerClick"] = async ({ type, params }) => {
  const propId = params.row?.[tableState.rowKey!];
  // const typeId = params.row?.type_id_val;
  // if (typeof propId === "undefined" || typeof typeId === "undefined") return;
  console.log(params);
  switch (type) {
    case "enum":
     
      break;
    case "delete":
     
      break;
    default:
      break;
  }
};


const edit_disabled=ref(false)

const edit_loading=ref(false)

// 单元格编辑保存
const tdSave = row => {
  edit_disabled.value = true;
  edit_loading.value = true;
  var curField= row.curField;
  if(curField=='factory_name'){
	curField="factory_id"
  }
  productSetTd({ apply_log_id: row.rowKey, field:curField, value: row.curval }).then(res => {
    edit_disabled.value = false;
    edit_loading.value = false;
    if (res.code == ResultEnum.SUCCESS) {
	  successMsg('修改成功');
      edit_model.value = false;
      tableDetailRef.value?.reloadData();
    } else {
      failMsg(res.message);
    }
  });
};









	
</script>

<style type="text/css">
	@import "./detail.scss";
</style>